"use strict";
cc._RF.push(module, '8b28c64f+dGdoqUCVqSM0NX', 'Net');
// scripts/utils/Net.js

"use strict";

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

if (!cc.sys.isNative) {
    window.io = require("SocketIO");
}

var net = cc.Class({
    extends: cc.Component,
    statics: {
        ip: "",
        sio: null,
        isPinging: false, //是否开启心跳
        fnDisconnect: null,
        handlers: {},

        inter1: 0, //定时器1
        inter2: 0, //定时器2
        addHandler: function addHandler(event, fn) {
            //add服务器返回事件
            if (this.handlers[event]) {
                cc.log("chat event:" + event + "' handler has been registered.");
                return;
            }

            var handler = function handler(data) {
                if (event != "disconnect" && typeof data == "string") {
                    cc.log("chat " + data);
                    try {
                        data = JSON.parse(data);
                    } catch (error) {
                        data = data;
                    }
                }
                fn(data);
            };

            this.handlers[event] = handler;
            if (this.sio) {
                cc.log("chat add register:function " + event);
                this.sio.on(event, handler);
            }
        },

        //清理所有注册事件
        clearHandler: function clearHandler() {
            for (var key in this.handlers) {
                delete this.handlers[key];
            }
        },

        //连接服务器
        connect: function connect(fnConnect, fnError) {
            var self = this;
            this.serverTime = Date.now();
            var opts = {
                'reconnection': false,
                'force new connection': true
                //'transports':['websocket', 'polling']
            };

            try {
                this.sio = window.io.connect(this.ip, opts);
            } catch (ex) {
                cc.log("socket connect erro:" + ex.message);
            }

            this.sio.on('connect', function (data) {

                self.sio.connected = true;
                try {
                    self.isPinging = false;
                    fnConnect(data);
                } catch (error) {
                    cc.log("connect error" + error);
                    fnError();
                }
            });

            //发生错误时触发
            this.sio.on('error', function (error) {
                cc.log("chat error + close:" + error);
                self.close();
            });

            //在断开连接时触发
            this.sio.on('disconnect', function (data) {
                cc.log("chat disconnect + reConnect");
                self.close();
            });

            //遇到连接错误
            this.sio.on('connect_error', function () {
                cc.log('chat connect_error + close');
                self.close();
            });

            //在连接超时后触发
            this.sio.on('connect_timeout', function () {
                cc.log('chat connect_timeout + reConnect');
                self.close();
            });

            //试图重新连接时被解雇
            this.sio.on('reconnect_attempt', function (data) {
                cc.log('chat reconnect_attempt close：' + data);
                self.close();
            });

            //重新连接尝试错误时触发
            this.sio.on('reconnect_error', function () {
                cc.log('chat reconnect_error + close');
                self.close();
            });

            //无法重新连接时触发
            this.sio.on('reconnect_failed', function () {
                cc.log('chat reconnect_failed + close');
                self.close();
            });

            for (var key in this.handlers) {
                var value = this.handlers[key];
                if (typeof value == "function") {
                    //if(key == 'DisConnect'){
                    //this.fnDisconnect = value;
                    //}
                    //else{
                    cc.log("chat register:function " + key);
                    this.sio.on(key, value);
                    //}
                }
            }
            this.startHearbeat();
        },

        //心跳包
        startHearbeat: function startHearbeat() {
            this.sio.on('rpongx', function (data) {
                cc.log('chat rpongx ' + data);
                self.serverTime = data;
                self.lastRecieveTime = Date.now();
            });
            this.lastRecieveTime = Date.now();
            var self = this;
            if (!self.isPinging) {
                self.isPinging = true;
                cc.game.on(cc.game.EVENT_HIDE, function () {
                    self.ping();
                });
                this.inter1 = setInterval(function () {
                    if (self.sio) {
                        self.ping();
                    }
                }.bind(this), 5000);
                this.inter2 = setInterval(function () {
                    if (self.sio) {
                        if (Date.now() - self.lastRecieveTime > 10000) {
                            cc.log("chat 未检测到心跳");
                            self.close();
                        }
                    }
                }.bind(this), 500);
            }
        },

        //聊天室时间同步
        getServerTime: function getServerTime() {
            return this.serverTime;
        },

        //心跳维持
        ping: function ping() {
            if (this.isConnect()) this.send("pongx", Date.now());
        },

        //断连
        close: function close() {
            cc.log('chat close');
            clearInterval(this.inter1);
            clearInterval(this.inter2);
            //this.clearHandler();
            if (this.sio && this.sio.connected) {
                cc.log("chat close1");
                this.sio.connected = false;
                this.sio.disconnect();
            }
            this.sio = null;
            //if(this.fnDisconnect){
            //    cc.log("chat close2");
            //this.fnDisconnect();
            //this.fnDisconnect = null;
            //}
        },

        //连接登录
        login: function login() {
            var self = this;
            var sd = {
                token: User.getLoginToken(),
                userid: User.getUserCode()
            };
            this.send("login", sd);
        },

        //发送房间聊天信息
        send_group_msg: function send_group_msg(msg) {
            cc.log("chat send_group_msg:" + msg);
            this.send("send_group_msg", msg);
        },

        //服务器是否连接
        isConnect: function isConnect() {
            return this.sio != null ? this.sio.connected : false;
        },

        //发送socket消息
        send: function send(event, data) {
            if (this.sio && this.sio.connected) {
                if (data != null && (typeof data === "undefined" ? "undefined" : _typeof(data)) == "object") {
                    data = JSON.stringify(data);
                    cc.log("chat " + data);
                }
                this.sio.emit(event, data);
            }
        },

        //加入房间
        joinRoom: function joinRoom(roomidStr, additionalStr, isrecont) {
            var data = {
                roomid: roomidStr,
                additional: additionalStr,
                chatrecord: isrecont
            };
            cc.log("chat join:" + roomidStr + "chatrecord:" + isrecont);
            this.send("join", data);
        },

        //离开房间
        leaveRoom: function leaveRoom(roomid) {
            cc.log("chat leave:" + roomid);
            this.send("leave", roomid);
        }

    }
});

cc._RF.pop();